<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-header">
        <el-icon class="logo-icon"><Lock /></el-icon>
        <h1 class="logo-text">VulnGuard</h1>
        <p class="login-subtitle">AI 漏洞检测平台</p>
      </div>
      
      <div class="login-form-container">
        <h2 class="login-title">用户登录</h2>
        <el-form 
          :model="loginForm" 
          :rules="loginRules" 
          ref="loginFormRef"
          class="login-form"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="el-icon-User"
              clearable
              :disabled="isLoading || isLocked"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-Lock"
              show-password
              :disabled="isLoading || isLocked"
              @input="checkPasswordStrength"
            />
            <!-- 密码强度指示器 -->
            <div v-if="loginForm.password.length > 0" class="password-strength">
              <div class="strength-indicators">
                <div 
                  v-for="(strength, index) in ['weak', 'medium', 'strong']" 
                  :key="index"
                  :class="[
                    'strength-bar',
                    `strength-${index + 1}`,
                    { active: passwordStrength >= index + 1 }
                  ]"
                ></div>
              </div>
              <span class="strength-text">{{ getPasswordStrengthText() }}</span>
            </div>
          </el-form-item>
          
          <!-- 图形验证码 -->
          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="el-icon-DocumentCopy"
                :disabled="isLoading || isLocked"
              />
              <div 
                class="captcha-image" 
                :class="{ disabled: isLoading || isLocked }"
                @click="refreshCaptcha"
                title="点击刷新验证码"
              >
                <img 
                  :src="captchaSrc" 
                  :alt="'验证码' + captchaTimestamp" 
                  v-if="captchaSrc"
                />
                <div class="captcha-placeholder" v-else>
                  <el-icon><Refresh /></el-icon>
                  <span>获取验证码</span>
                </div>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="loginForm.rememberMe" :disabled="isLoading || isLocked">记住登录状态</el-checkbox>
              <router-link to="/forgot-password" class="forgot-password-link" :disabled="isLoading || isLocked">忘记密码？</router-link>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleLogin" 
              class="login-button"
              :loading="isLoading"
              :disabled="isLoading || isLocked"
            >
              {{ isLocked ? `账号已锁定，请${lockCountdown}秒后重试` : (isLoading ? '登录中...' : '登录') }}
            </el-button>
          </el-form-item>
          
          <!-- 安全提示 -->
          <div class="security-tip">
            <el-alert
              title="安全提示"
              type="info"
              :closable="false"
              show-icon
              description="请勿使用弱密码，建议包含大小写字母、数字和特殊符号"
              :title-size="'small'"
            />
          </div>
          
          <!-- 登录成功后将跳转到相应权限的页面 -->
        </el-form>
      </div>
    </div>
    
    <!-- 背景装饰元素 -->
    <div class="bg-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import apiService from '../services/apiService.js'

const router = useRouter()
const loginFormRef = ref(null)
const isLoading = ref(false)
const isLocked = ref(false)
const lockCountdown = ref(0)
const passwordStrength = ref(0)
const captchaTimestamp = ref(Date.now())
const captchaId = ref('') // 添加验证码ID引用

// 登录失败次数限制相关
const failedAttempts = ref(0)
const MAX_ATTEMPTS = 5
const LOCK_DURATION = 60 // 锁定时间（秒）

// 验证码图片URL
const captchaSrc = ref('')

// 不再强制禁用模拟数据，让apiService决定数据源
console.log('LoginView初始化，允许apiService管理数据源设置');

// 登录表单数据
const loginForm = reactive({
  username: localStorage.getItem('rememberedUsername') || '',
  password: '',
  captcha: '',
  rememberMe: !!localStorage.getItem('rememberedUsername')
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, message: '密码长度至少为 1 个字符', trigger: 'blur' } // 降低要求，方便测试
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' }
  ]
}

// 检查密码强度
const checkPasswordStrength = (value) => {
  if (!value) {
    passwordStrength.value = 0
    return
  }
  
  const hasLower = /[a-z]/.test(value)
  const hasUpper = /[A-Z]/.test(value)
  const hasNumber = /[0-9]/.test(value)
  const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value)
  const hasMinLength = value.length >= 8
  
  const strengthCount = [hasLower, hasUpper, hasNumber, hasSpecial, hasMinLength].filter(Boolean).length
  
  if (strengthCount <= 2) {
    passwordStrength.value = 1 // 弱
  } else if (strengthCount <= 4) {
    passwordStrength.value = 2 // 中
  } else {
    passwordStrength.value = 3 // 强
  }
}

// 获取密码强度文本
const getPasswordStrengthText = () => {
  const texts = ['', '弱', '中', '强']
  return texts[passwordStrength.value] || ''
}

// 刷新验证码
const refreshCaptcha = async () => {
  if (isLoading.value || isLocked.value) {
    console.log('验证码刷新已跳过：登录中或账号已锁定');
    return;
  }
  
  try {
    console.log('开始刷新验证码...');
    captchaSrc.value = ''; // 清空旧图片，显示加载状态
    loginForm.captcha = ''; // 重置验证码输入框
    
    // 添加防抖，避免频繁点击
    if (window.captchaRefreshTimer) {
      clearTimeout(window.captchaRefreshTimer);
    }
    window.captchaRefreshTimer = setTimeout(() => {}, 1000);
    
    // 执行验证码获取
    const result = await apiService.getCaptcha();
    // 确保captchaId正确设置
    if (typeof result === 'object' && result.imageUrl && result.captchaId) {
      captchaSrc.value = result.imageUrl;
      captchaId.value = result.captchaId;
      console.log('验证码刷新成功，已获取验证码ID:', captchaId.value);
    } else {
      // 处理兼容情况
      captchaSrc.value = result;
      // 尝试从apiService获取最新的验证码ID
      if (apiService.getCaptchaId) {
        captchaId.value = apiService.getCaptchaId();
        console.log('验证码刷新成功，从apiService获取验证码ID:', captchaId.value);
      }
    }
  } catch (error) {
    console.error('刷新验证码失败:', error);
    
    // 更友好的错误提示
    let errorMsg = '获取验证码失败';
    if (error.message.includes('Network') || error.message.includes('连接')) {
      errorMsg = '网络连接异常，无法获取验证码';
    } else if (error.message.includes('404')) {
      errorMsg = '验证码服务暂不可用';
    } else if (error.message.includes('50')) {
      errorMsg = '服务器繁忙，请稍后重试';
    }
    
    ElMessage.error(errorMsg);
    
    // 如果有旧的验证码，尝试保留
    if (!captchaSrc.value && sessionStorage.getItem('currentCaptchaId')) {
      console.log('尝试保留旧的验证码状态');
    }
  }
}

// 初始化验证码和恢复验证码ID
const initializeCaptcha = async () => {
  try {
    console.log('初始化验证码...');
    
    // 尝试恢复验证码ID（如果页面刷新）
    if (apiService.restoreCaptchaId) {
      const restoredId = apiService.restoreCaptchaId();
      if (restoredId) {
        console.log('验证码ID恢复成功，将获取新的验证码图片');
      } else {
        console.log('无可用验证码ID可恢复');
      }
    }
    
    // 刷新获取新的验证码
    await refreshCaptcha();
  } catch (error) {
    console.error('初始化验证码失败:', error);
    
    // 初始化失败时的兜底逻辑
    setTimeout(() => {
      if (!captchaSrc.value) {
        console.log('验证码初始化失败后重试...');
        refreshCaptcha();
      }
    }, 1000);
  }
}

// 锁定账号并倒计时
const lockAccount = () => {
  isLocked.value = true
  lockCountdown.value = LOCK_DURATION
  
  const timer = setInterval(() => {
    lockCountdown.value--
    if (lockCountdown.value <= 0) {
      clearInterval(timer)
      isLocked.value = false
      failedAttempts.value = 0
      refreshCaptcha()
    }
  }, 1000)
}

// 处理登录
const handleLogin = async () => {
  console.log('LoginView: 登录流程开始');
  
  // 不再禁用模拟数据，让apiService管理数据源
  console.log('LoginView: 允许apiService管理数据源设置');
  
  console.log('==================== 登录流程开始 ====================');
  
  // 表单验证
  console.log('登录按钮被点击，检查表单引用和锁定状态...');
  if (!loginFormRef.value || isLocked.value) {
    console.log('表单引用不存在或账号已锁定:', { loginFormRefExists: !!loginFormRef.value, isLocked: isLocked.value });
    return
  }
  
  // 正确使用Element Plus的validate方法（返回Promise）
    console.log('开始执行表单验证...');
    const isValid = await loginFormRef.value.validate();
    console.log('LoginView: 表单验证结果:', isValid);
    if (!isValid) {
      console.log('表单验证失败，终止登录流程');
      return
    }
    
    // 表单验证通过，准备发送登录请求
    console.log('表单验证通过，准备发送登录请求');
  
  try {
      console.log('表单验证通过，开始登录请求处理...');
      isLoading.value = true
      console.log('设置加载状态为true');
      
      // 清除之前的错误提示
      ElMessage.closeAll();
      console.log('清除之前的错误提示');
      
      // 不再清除或禁用模拟数据设置
      console.log('允许apiService使用已配置的数据源设置');
      
      console.log('开始登录流程，使用账号:', loginForm.username, '和验证码:', loginForm.captcha || '未提供');
      console.log('apiService.login方法存在:', typeof apiService.login === 'function');
      
      console.log('开始调用登录API...');
      
      // apiService.login现在已支持四个参数，包括captchaId
      console.log('准备调用apiService.login...');
      console.log('参数检查 - apiService.login方法签名:', apiService.login.toString());
      console.log('传递的参数 - username:', loginForm.username);
      console.log('传递的参数 - password:', '******');
      console.log('传递的参数 - captcha:', loginForm.captcha);
      console.log('传递的参数 - captchaId:', captchaId.value);
      
      const response = await apiService.login(loginForm.username, loginForm.password, loginForm.captcha, captchaId.value);
      console.log('登录API调用完成，收到响应:', response);
    console.log('apiService.login调用成功完成，收到响应');
    
    console.log('收到登录API响应:', JSON.stringify(response));
    
    // 简化响应处理 - 因为apiService已经确保返回标准格式
    if (response?.success && response?.data?.token) {
      console.log('登录响应验证成功，包含有效的token和用户信息');
      // 重置失败次数
      failedAttempts.value = 0;
      await handleLoginSuccess(response.data);
    } else {
      const errorMsg = '登录响应无效或不完整';
      console.error(errorMsg, '响应数据:', response);
      throw new Error(errorMsg);
    }
  } catch (error) {
    console.error('登录失败:', error.message, error);
    // 登录失败处理
    failedAttempts.value++;
    console.log('登录失败次数:', failedAttempts.value);
    
    // 账号锁定检查
    if (failedAttempts.value >= MAX_ATTEMPTS) {
      ElMessage.error(`账号已被锁定，请${LOCK_DURATION}秒后重试`);
      lockAccount();
      return;
    }
    
    // 提供更友好的错误消息和分类处理
    let errorMessage;
    let shouldRefreshCaptcha = true;
    
    if (error.message.includes('网络') || error.message.includes('连接')) {
      errorMessage = '网络错误，请检查您的网络连接后重试';
    } else if (error.message.includes('格式')) {
      errorMessage = '数据格式错误，请刷新页面后重试';
    } else if (error.message.includes('验证码')) {
      errorMessage = error.message || '验证码错误或已过期';
    } else if (error.message.includes('401') || error.message.includes('认证') || error.message.includes('密码') || error.message.includes('用户名')) {
      errorMessage = '用户名或密码错误';
      // 计算剩余尝试次数
      const remainingAttempts = MAX_ATTEMPTS - failedAttempts.value;
      if (remainingAttempts > 0) {
        errorMessage += `，还有${remainingAttempts}次尝试机会`;
      }
    } else if (error.message.includes('429') || error.message.includes('请求过于频繁')) {
      errorMessage = '请求过于频繁，请稍后再试';
      shouldRefreshCaptcha = false; // 频率限制时不刷新验证码
    } else if (error.message.includes('50')) {
      errorMessage = '服务器临时异常，请稍后重试';
    } else {
      errorMessage = error.message || '登录失败，请检查您的凭据';
    }
    
    ElMessage.error(errorMessage);
    
    // 根据错误类型决定是否刷新验证码
    if (shouldRefreshCaptcha) {
      // 延迟一小段时间再刷新验证码，给用户时间看到错误信息
      setTimeout(() => {
        refreshCaptcha();
      }, 500);
    }
  } finally {
    isLoading.value = false;
  }
}

// 处理登录成功
const handleLoginSuccess = async (response) => {
  try {
    // 保存登录状态 - 增加防御性检查
    const token = response?.token;
    const user = response?.user || {};
    
    if (!token) {
      throw new Error('登录成功但未获取到token');
    }
    
    // 保存到本地存储或会话存储
    if (loginForm.rememberMe) {
      localStorage.setItem('token', token)
      localStorage.setItem('rememberedUsername', loginForm.username)
    } else {
      sessionStorage.setItem('token', token)
      localStorage.removeItem('rememberedUsername')
    }
    localStorage.setItem('user', JSON.stringify(user))
    
    // 重置失败次数
    failedAttempts.value = 0
    
    // 安全地获取用户名
    const displayName = user?.name || user?.username || '用户';
    ElMessage.success(`欢迎回来，${displayName}`)
    
    // 跳转到首页
    router.push('/')
  } catch (error) {
    console.error('处理登录成功逻辑时出错:', error);
    ElMessage.error('登录信息处理失败，请重试');
  }
}

// 显示忘记密码
const showForgotPassword = () => {
  ElMessageBox.alert(
    '请联系系统管理员重置密码',
    '忘记密码',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 组件卸载时清理资源
onUnmounted(() => {
  console.log('Login组件卸载，清理资源...');
  
  // 清理验证码资源
  if (apiService.cleanupCaptcha) {
    apiService.cleanupCaptcha();
  }
  
  // 清理定时器
  if (window.captchaRefreshTimer) {
    clearTimeout(window.captchaRefreshTimer);
    delete window.captchaRefreshTimer;
  }
  
  // 关闭所有消息提示
  ElMessage.closeAll();
});

// 检查是否有记住的用户名和已登录状态
onMounted(() => {
  console.log('LoginView: 页面初始化，允许apiService管理数据源');
  // 不再移除或禁用模拟数据设置
  
  console.log('Login组件挂载');
  
  // 检查记住的用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.rememberMe = true
    console.log('已恢复记住的用户名');
  }
  
  // 检查是否已登录
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (token) {
    console.log('检测到有效token，尝试直接登录');
    // 可以在这里验证token是否有效
    router.push('/')
    return;
  }
  
  // 初始化验证码
  initializeCaptcha()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  position: relative;
  overflow: hidden;
}

.login-wrapper {
  background: #ffffff;
  border-radius: 24px;
  box-shadow: 0 20px 80px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 480px;
  padding: 40px;
  z-index: 10;
  transition: all 0.3s ease;
}

.login-wrapper:hover {
  box-shadow: 0 25px 100px rgba(0, 0, 0, 0.15);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

.logo-text {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.login-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.login-form-container {
  margin-top: 16px;
}

.login-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 24px;
  text-align: center;
}

.login-form {
  width: 100%;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.login-form :deep(.el-input) {
  border-radius: 12px;
  transition: all 0.3s ease;
}

.login-form :deep(.el-input:hover .el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.login-form :deep(.el-input__wrapper.is-focused) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-password-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.forgot-password-link:hover {
  color: #66b1ff;
}

.forgot-password-link:disabled {
  color: #909399;
  cursor: not-allowed;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 12px;
  background: linear-gradient(135deg, #409eff 0%, #2979ff 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.login-button:disabled {
  background: #dcdfe6;
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 验证码样式 */
.captcha-container {
  display: flex;
  gap: 12px;
  align-items: stretch;
}

.captcha-container :deep(.el-input) {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.captcha-image:hover:not(.disabled) {
  border-color: #409eff;
  background: #ecf5ff;
}

.captcha-image.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.captcha-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.captcha-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #606266;
  font-size: 12px;
}

.captcha-placeholder .el-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

/* 密码强度指示器样式 */
.password-strength {
  margin-top: 8px;
  padding: 0 4px;
}

.strength-indicators {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background: #e6e6e6;
  transition: all 0.3s ease;
}

.strength-bar.strength-1.active {
  background: #f56c6c;
}

.strength-bar.strength-2.active {
  background: #e6a23c;
}

.strength-bar.strength-3.active {
  background: #67c23a;
}

.strength-text {
  font-size: 12px;
  color: #606266;
}

/* 安全提示样式 */
.security-tip {
  margin: 16px 0;
}

.security-tip :deep(.el-alert__title) {
  font-size: 14px;
}

.security-tip :deep(.el-alert__description) {
  font-size: 12px;
}

/* 演示账号样式 */
.demo-account {
  margin-top: 24px;
}

.divider-text {
  font-size: 14px;
  color: #909399;
}

.account-info {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 12px;
  margin-top: 16px;
}

.account-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

.account-info code {
  background: #ffffff;
  padding: 2px 8px;
  border-radius: 4px;
  color: #f56c6c;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
}

.demo-captcha {
  color: #409eff !important;
  font-size: 13px;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
  background: linear-gradient(135deg, #409eff 0%, #2979ff 100%);
}

.circle-1 {
  width: 400px;
  height: 400px;
  top: -100px;
  left: -100px;
}

.circle-2 {
  width: 300px;
  height: 300px;
  bottom: -150px;
  right: -100px;
}

.circle-3 {
  width: 200px;
  height: 200px;
  top: 50%;
  right: -50px;
  transform: translateY(-50%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-wrapper {
    margin: 20px;
    padding: 32px 24px;
    border-radius: 16px;
  }
  
  .logo-icon {
    font-size: 36px;
  }
  
  .logo-text {
    font-size: 24px;
  }
  
  .captcha-container {
    flex-direction: column;
  }
  
  .captcha-image {
    width: 100%;
    height: 48px;
  }
  
  .decoration-circle {
    display: none;
  }
}
</style>